<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="company_box box-card">
        <el-tabs v-model="activeName">
          <el-tab-pane label="角色管理" name="role">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="editRoleDialog = true"
            >新增角色</el-button>
            <el-table :data="roles" style="width: 100%" border>
              <el-table-column type="index" label="序号" width="150" />
              <el-table-column
                prop="name"
                label="角色名"
                width="180"
                sortable
              />
              <el-table-column prop="description" label="描述" sortable />
              <el-table-column
                prop="address"
                label="操作"
                width="250"
                align="center"
              >
                <template v-slot="{ row }">
                  <el-button
                    type="text"
                    size="mini"
                    @click="onsetPermission(row)"
                  >分配权限</el-button>
                  <el-button
                    type="text"
                    size="mini"
                    @click="editRole(row)"
                  >修改</el-button>
                  <el-button
                    type="text"
                    size="mini"
                    @click="delRole(row.id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              :current-page.sync="page.page"
              :page-size="page.pagesize"
              layout="total, prev, pager, next"
              :total="total"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>
          <el-tab-pane label="公司信息" name="info">
            <el-form
              ref="infoForm"
              :disabled="true"
              :model="infoForm"
              label-width="80px"
            >
              <el-form-item label="企业名称">
                <el-input v-model="infoForm.name" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="infoForm.companyAddress" />
              </el-form-item>
              <el-form-item label="公司电话">
                <el-input v-model="infoForm.companyPhone" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="infoForm.mailbox" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="infoForm.remarks" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>

    <!-- 对话框 -->
    <el-dialog
      :title="titleText"
      :visible.sync="editRoleDialog"
      width="30%"
      @close="onClose"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="form.description" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialog = false">取 消</el-button>
        <el-button type="primary" @click="onSave">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      :title="'为【' + permissionTitle + '】分配权限'"
      :visible.sync="setPermissionDialog"
      width="50%"
      @close="onPermissionClose"
    >
      <el-tree
        v-if="setPermissionDialog"
        ref="setPermissionTree"
        check-strictly
        node-key="id"
        :default-checked-keys="defaultKeys"
        show-checkbox
        default-expand-all
        icon-class=" "
        :data="permissionList"
        :props="defaultProps"
      />

      <span slot="footer" class="dialog-footer">
        <el-button @click="onPermissionClose">取 消</el-button>
        <el-button type="primary" :loading="permissionLoading" @click="onSetPermissionSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getPermissionList, setPermissionToRole } from '@/api/permission'
import { transListToTree } from '@/utils'
import {
  getroleList,
  delrole,
  getroleByid,
  updateRole,
  addRole,
  getCompany
} from '@/api/company'
export default {
  name: 'Settings',
  data() {
    return {
      activeName: 'role',
      roles: [],
      page: {
        page: 1,
        pagesize: 10
      },
      total: 0,
      editRoleDialog: false,
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入活动角色名称', trigger: 'blur' },
          { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入活动角色描述', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ]
      },
      infoForm: {
        name: '',
        companyAddress: '',
        companyPhone: '',
        mailbox: '',
        remarks: ''
      },
      setPermissionDialog: false,
      permissionTitle: '',
      permissionList: [],
      defaultProps: {
        label: 'name'
      },
      defaultKeys: [],
      roleId: '',
      permissionLoading: false
    }
  },
  computed: {
    titleText() {
      return (this.form.id ? '编辑' : '新增') + '角色'
    }
  },
  created() {
    this.loadRoleList()
    this.loadCompany()
  },

  methods: {
    // 获取表格信息
    async loadRoleList() {
      const res = await getroleList(this.page)
      this.roles = res.rows
      this.total = res.total
    },
    // 切换页
    handleCurrentChange(val) {
      this.page.page = val
      this.loadRoleList()
    },
    // 删除
    delRole(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          try {
            await delrole(id)
            this.$message.success('删除成功！')
            this.loadRoleList()
          } catch (err) {
            return
          }
        })
        .catch(() => {})
    },
    // 修改
    async editRole(row) {
      const res = await getroleByid(row.id)
      this.editRoleDialog = true
      this.form = res
    },
    // 确认
    async onSave() {
      try {
        await this.$refs.form.validate()
        if (this.form.id) {
          // 更新
          await updateRole(this.form)
        } else {
          // 新增
          await addRole(this.form)
        }
        this.editRoleDialog = false
        this.$message.success('操作成功！')
        this.loadRoleList()
      } catch (err) {
        return
      }
    },
    // 关闭
    onClose() {
      this.$refs.form.resetFields()
      setTimeout(() => {
        this.form = {
          name: '',
          description: ''
        }
      }, 200)
    },
    async loadCompany() {
      const res = await getCompany()
      this.infoForm = res[0]
    },
    // 分配权限
    async onsetPermission(row) {
      this.roleId = row.id
      this.permissionTitle = row.name
      this.setPermissionDialog = true
      this.permissionList = transListToTree('0', await getPermissionList())
      this.defaultKeys = (await getroleByid(row.id)).permIds
    },
    // 保存分配权限
    async onSetPermissionSave() {
      try {
        this.permissionLoading = true
        const permissionIds = this.$refs.setPermissionTree.getCheckedKeys()
        if (!permissionIds.length) return this.$message.error('请选择!')
        await setPermissionToRole({
          permIds: permissionIds,
          id: this.roleId
        })
        this.$message.success('成功！')
        this.onPermissionClose()
      } catch (err) {
        console.dir(err)
      }
      this.permissionLoading = false
    },
    onPermissionClose() {
      this.setPermissionDialog = false
      this.defaultKeys = []
    }
  }
}
</script>

<style scoped lang="scss">
.company_box {
  ::v-deep.el-tabs__item {
    font-size: 18px;
    padding: 0 40px;
    width: 150px;
    text-align: center;
  }
}
.el-pagination {
  display: flex;
  justify-content: flex-end;
}
</style>
